package com.example.administrator.schoolblog;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.borax12.materialdaterangepicker.date.DatePickerDialog;
import com.bumptech.glide.Glide;
import com.example.administrator.schoolblog.Beans.BlogUser;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.hdodenhof.circleimageview.CircleImageView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class EditinfoActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener{
    private LinearLayout edit_avatar;
    private static final int RESULT_CHOOSE_LOCATION = 1;
    private static final int RESULT_CHOOSE_PHOTO = 2;
    private CircleImageView avatar;
    private String picPath;
    private TextView location;
    private LinearLayout edit_birth;
    private TextView birth;
    private LinearLayout edit_location;
    private LinearLayout edit_sex;
    private TextView sex;
    private String userId;
    private BlogUser userInfo;
    private EditText edit_nickname;
    private EditText edit_email;
    private EditText edit_yuan;
    private EditText signature;
    private TextView username;
    private FloatingActionButton commit;
    private BmobFile upImageFile;
    private String userIconUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
        setContentView(R.layout.blog_user_edit_info);
        Bmob.initialize(this,"b5d62a501dc94902d3f8672a1b5fc2ab","Bmob");
        initView();
        refreshView();
    }

    /**
     * 初始化视图
     */
    private void initView(){
        //获取主键
        Intent new_intent = getIntent();
        userId = new_intent.getStringExtra("UserId");
        Toolbar toolbar =(Toolbar) findViewById(R.id.blog_userinfo_edit_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //实例化，点击
        edit_avatar = (LinearLayout) findViewById(R.id.edit_avatar);
        edit_avatar.setOnClickListener(new OnclickListener());
        avatar = (CircleImageView) findViewById(R.id.avatar);
        location = (TextView) findViewById(R.id.location);
        edit_birth = (LinearLayout) findViewById(R.id.edit_birth);
        edit_birth.setOnClickListener(new OnclickListener());
        birth = (TextView) findViewById(R.id.birth);
        edit_location = (LinearLayout) findViewById(R.id.edit_location);
        edit_location.setOnClickListener(new OnclickListener());
        edit_sex = (LinearLayout) findViewById(R.id.edit_sex);
        edit_sex.setOnClickListener(new OnclickListener());
        sex = (TextView) findViewById(R.id.sex);
        edit_nickname = (EditText) findViewById(R.id.edit_nickname);
        edit_email = (EditText) findViewById(R.id.edit_email);
        edit_yuan = (EditText) findViewById(R.id.edit_yuan);
        signature = (EditText) findViewById(R.id.edit_sign);
        commit = (FloatingActionButton) findViewById(R.id.commit_fab);
        commit.setOnClickListener(new OnclickListener());
        username = (TextView) findViewById(R.id.username);
    }
    /**
     * 点击函数
     */
    public class OnclickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.edit_avatar:
                    MultiImageSelectorActivity.startSelect(EditinfoActivity.this,
                            RESULT_CHOOSE_PHOTO, 1, MultiImageSelectorActivity.MODE_SINGLE);
                    break;
                case R.id.edit_birth:
                    Calendar now = Calendar.getInstance();
                    DatePickerDialog dpd = DatePickerDialog.newInstance(
                            EditinfoActivity.this,
                            now.get(Calendar.YEAR),
                            now.get(Calendar.MONTH),
                            now.get(Calendar.DAY_OF_MONTH));
                    dpd.show(getFragmentManager(), "Datepickerdialog");
                    break;
                case R.id.edit_location:
                    ChooseLocationActivity.actionStart(EditinfoActivity.this, RESULT_CHOOSE_LOCATION);
                    break;
                case R.id.edit_sex:
                    showSexChoose();
                    break;
                case R.id.commit_fab:
                    updateUserInfo();
                    break;
            }
        }
    }
    /**
     * 选择头像回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CHOOSE_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> mSelectPath =
                        data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);

                for (String p : mSelectPath) {
                    Picasso.with(EditinfoActivity.this)
                            .load(new File(p))
                            .resize(200, 200)
                            .centerCrop()
                            .into(avatar);
                    picPath = p;
                    //Toast.makeText(this, picPath, Toast.LENGTH_SHORT).show();
                }
            }
        }else if(requestCode == RESULT_CHOOSE_LOCATION) {
            if(resultCode == RESULT_OK){
                location.setText(data.getStringExtra("location"));
            }
        }
    }
    //生日选择回调
    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth, int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
        String date = Integer.toString(year) + "-"
                + Integer.toString(monthOfYear + 1) + "-"
                + Integer.toString(dayOfMonth);

        birth.setText(date);
    }

    /**
     * 性别选择函数
     */
    private void showSexChoose(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(EditinfoActivity.this);
        final String[] sexs = {getString(R.string.sex_man), getString(R.string.sex_woman)};
        builder.setTitle("请选择性别");
        int defaultWhich;
        if(sex.getText().toString().equals(sexs[1])) {
            defaultWhich = 1;
        } else{
            defaultWhich = 0;
        }
        builder.setSingleChoiceItems(sexs, defaultWhich,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sex.setText(sexs[which]);
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    /**
     * 刷新个人信息
     */
    private void refreshView(){
        BmobQuery<BlogUser> getUserInfo = new BmobQuery<BlogUser>();
        getUserInfo.getObject(userId, new QueryListener<BlogUser>() {
            @Override
            public void done(BlogUser blogUser, BmobException e) {
                if (e==null){
                    if (blogUser.getUserIconUrl()!=null){
                        Glide.with(EditinfoActivity.this).load(blogUser.getUserIconUrl()).into(avatar);
                    }
                    edit_email.setText(blogUser.getEmail());
                    birth.setText(blogUser.getBirthday());
                    username.setText(blogUser.getUsername());
                    edit_nickname.setText(blogUser.getNickname());
                    signature.setText(blogUser.getSignature());
                    sex.setText(blogUser.getSex());
                    edit_yuan.setText(blogUser.getCollege());
                    location.setText(blogUser.getLocation());
                }
            }
        });
    }
    /**
     * 个人信息上传
     */
    private void updateUserInfo(){
        userInfo = new BlogUser();
        if(picPath!=null){
            BmobQuery<BlogUser> getUserInfo = new BmobQuery<BlogUser>();
            getUserInfo.getObject(userId, new QueryListener<BlogUser>() {
                @Override
                public void done(BlogUser blogUser, BmobException e) {
                    if (e==null) {
                        if (blogUser.getUserIconUrl() != null) {
                            BmobFile del_file = new BmobFile();
                            del_file.setUrl(blogUser.getUserIconUrl());
                            del_file.delete(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    upInfoWithImg();
                                }
                            });
                        }else {
                            upInfoWithImg();
                        }
                    }
                }
            });
        }else{
            upInfoNoImg();
        }
        //Toast.makeText(this, userInfo.getUserIconUrl(), Toast.LENGTH_SHORT).show();

    }
    /**
     * 有头像信息更新
     */
    private void upInfoWithImg(){
        upImageFile = new BmobFile(new File(picPath));
        upImageFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    userIconUrl = upImageFile.getFileUrl();
                    userInfo.setUserIconUrl(userIconUrl);
                    //Toast.makeText(EditinfoActivity.this, userInfo.getUserIconUrl(), Toast.LENGTH_SHORT).show();
                    userInfo.setNickname(edit_nickname.getText().toString());
                    userInfo.setBirthday(birth.getText().toString());
                    userInfo.setLocation(location.getText().toString());
                    userInfo.setCollege(edit_yuan.getText().toString());
                    userInfo.setSex(sex.getText().toString());
                    userInfo.setEmail(edit_email.getText().toString());
                    userInfo.setSignature(signature.getText().toString());
                    userInfo.update(userId, new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                Toast.makeText(EditinfoActivity.this, "个人信息更新成功!", Toast.LENGTH_SHORT).show();
                                finish();
                            }else {
                                Toast.makeText(EditinfoActivity.this, "哎呀，更新失败，请重试!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        });
    }
    /**
     * 无头像更新信息
     */
    private void upInfoNoImg(){
        userInfo.setNickname(edit_nickname.getText().toString());
        userInfo.setBirthday(birth.getText().toString());
        userInfo.setLocation(location.getText().toString());
        userInfo.setCollege(edit_yuan.getText().toString());
        userInfo.setSex(sex.getText().toString());
        userInfo.setEmail(edit_email.getText().toString());
        userInfo.setSignature(signature.getText().toString());
        userInfo.update(userId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    Toast.makeText(EditinfoActivity.this, "个人信息更新成功!", Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    Toast.makeText(EditinfoActivity.this, "哎呀，更新失败，请重试!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
